//
// Copyright (C) [2024] Xingyun Integrated Circuit, Inc.
//
// GreenCode was a private technology asset of Xingyun Integrated Circuit， Inc （Confidential）
//  Author: Shawn.Tan
//  Date : 2025.10.28
//
//  History : Initial Version 2025.10.28
//
//
#include "SimplePeState.h"

#include "Log.h"
#include "Register.h"

using namespace std;

/*!
  \file SimplePeState.cc
  \brief Code managing PE state save and restore.
*/

namespace Green {

  SimpleRegisterState::SimpleRegisterState(Register* pReg)
    : mpRegister(pReg), mValue(0)
  {
    mValue = mpRegister->Value();
  }

  void SimplePeState::SaveState(Generator* pGen, const std::vector<Register* >& rRegContext)
  {
    mRegisterStates.clear();
    mRegisterStates.reserve(rRegContext.size());

    transform(rRegContext.cbegin(), rRegContext.cend(), back_inserter(mRegisterStates),
      [](Register* pReg) { return SimpleRegisterState(pReg); });
  }

  bool SimplePeState::RestoreState()
  {
    bool state_changed = false;
    for (auto & reg_state : mRegisterStates) {
      auto reg_ptr = reg_state.mpRegister;
      if (reg_ptr->Value() != reg_state.mValue) {
        reg_ptr->SetValue(reg_state.mValue);
        LOG(notice) << "{PeState::RestoreState} restore register " << reg_ptr->Name() << " to 0x" << hex << reg_state.mValue << endl;
        state_changed = true;
      }
    }
    return state_changed;
  }

}
